package diva.canvaslibrary.client.particles;

import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.dom.client.ImageElement;

import diva.gwtlib.client.Point;

public class Particle {

  static final int FOV = 40;
  private final int screenHalfHeight;
  private final int screenHalfWidth;
  private final Vector position = new Vector(0, 0, 0);
  private final Vector vel = new Vector(0, 0, 0);
  private final ImageElement image;
  private boolean enabled;

  public Particle(ImageElement image, Point position, Size screenSize) {
    this.image = image;
    screenHalfHeight = screenSize.getHeight() / 2 - 360;
    screenHalfWidth = screenSize.getWith() / 2;
    reset(position);
  }

  public void draw(Context2d canvas2d) {
    double x3d = position.getX();
    double y3d = position.getY();
    double z3d = position.getZ();
    double scale = FOV / (FOV + z3d);
    double x2d = x3d * scale + screenHalfWidth;
    double y2d = y3d * scale + screenHalfHeight;
    scale *= 9;
    if (scale > 0) canvas2d.drawImage(image, x2d - scale, y2d - scale, scale * 2, scale * 2);
  }

  public boolean isEnabled() {
    return enabled;
  }

  public void reset(Point value) {
    position.reset(value.getX(), value.getY(), 0);
    vel.reset(Math.random() * 20 - 10, Math.random() * 20 - 10, Math.random() * 20 - 4);
    enabled = true;
  }

  public void update(double drag, double gravity) {
    if (enabled) {
      position.plusEq(vel);
      vel.multiplyEq(drag);
      vel.addY(gravity);
      if (position.getY() < -70) disable();
    }
  }

  private void disable() {
    enabled = false;
  }
}
